package xml_tests.XMLParsing;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlTagsWithLinesTree extends DefaultHandler{

	int level = 0;
	String docName;

	public XmlTagsWithLinesTree(String docName) {
		this.docName = docName;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            parser.parse(docName, this);
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfig error");
        } catch (SAXException e) {
            System.out.println("SAXException : xml not well formed");
        } catch (IOException e) {
            System.out.println("IO error");
        }
	}
	
	public void startDocument() {
		System.out.println(docName);
	}
/**
 * catalog.xml
 *  +-catalog
 *  |  +-book
 *  |  |  +-isbn
 *  |  |  +-authors
 *  |  |  |  +-author
 **/
	public void startElement(String ns, String sname, String qName, Attributes atts) {
		int i;
		//if new element started, increase the level
		level += 1;
/**
 * For additional blank line
		for (i = 0; i < level; i++) {
			System.out.print("  |");
		}
		System.out.println();
**/
		//print ___| for level-1 times
		for (i = 1; i < level; i++) {
			System.out.print("  |");
		}
		System.out.println("  +-" + qName);
	}

	public void endElement(String ns, String sname, String qName) {
		level -= 1;
	}
}
